// --------------------------------------------------------------------------------------------------------------------
// <copyright file="VirtualDriveFeedbackAgent.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Microsoft.Robotics.Navigation.Runtime.Perception
{
        using System.IO;
    using System.Runtime.Serialization;    

    using Microsoft.Robotics.Hardware.DAC;
    using Microsoft.Robotics.Hardware.Runtime.DAC;
    using Microsoft.Robotics.IO;
    using Microsoft.Robotics.Numerics;
    using Microsoft.Robotics.Runtime;

    /// <summary>
    /// Agent that maintains an estimation of robot pose (x, y, heading) given drive odometry along
    /// with angular speed on the y-axis of the gyro.
    /// </summary>
    [DataContract]
    public class VirtualDriveFeedbackAgent : SynchronizedConsumerProducerAgent<SimpleAgentMessage<DriveFeedbackState>, GyroscopeMessage, SimpleAgentMessage<DriveFeedbackState>>
    {
        /// <summary>
        /// The maximum allowed discrepancy between the originating times of the two messages being synchronized
        /// </summary>
        private const int DefaultSyncTolerance = 5;

        /// <summary>
        /// Tests have shown that collecting about 16 seconds of data (400 samples) results in descent in-run bias removal. 
        /// This field is configurable to allow some consumers of this service (i.e. short recording tests) to override the
        /// default and use a shorter sampling session, which is OK for the short runs
        /// </summary>
        [DataMember(Name = "RequiredGyroMeasurementsForCalibration")]
        private readonly int requiredGyroMeasurementsForCalibration;

        /// <summary>
        /// The name of the agent producing gyro data to which we subscribe.
        /// </summary>
        [DataMember(Name = "GyroProducer")]
        private readonly string gyroProducer;

        /// <summary>
        /// The name of the agent producing odometry data to which we subscribe.
        /// </summary>
        [DataMember(Name = "OdometryProducer")]
        private readonly string odometryProducer;
     
        /// <summary>
        /// Robot configuration folder, which contains gyroscope calibration information.
        /// </summary>
        [DataMember(Name = "RobotConfigFolder")]
        private string robotConfigFolder;

        /// <summary>
        /// Virtual drive feedback logic being encapsulated by this agent.
        /// </summary>
        private VirtualDriveFeedback virtualDriveFeedback;

        /// <summary>
        /// Gyro calibration data.
        /// </summary>
        private GyroCalibration gyroCalibration;

        /// <summary>
        /// Initializes a new instance of the VirtualDriveFeedbackAgent class
        /// </summary>
        /// <param name="name">Agent name</param>
        /// <param name="odometryProducer">The name of the heartbeat agent to which we subscribe.</param>
        /// <param name="gyroProducer">The name of the agent to which we subscribe.</param>
        /// <param name="robotConfigFolder">Robot config folder with gyro calibration info</param>        
        /// <param name="requiredGyroMeasurementsForCalibration">Number of gyro samples to collect and calibrate before robot can move</param>        
        public VirtualDriveFeedbackAgent(
            string name,
            IProducer<SimpleAgentMessage<DriveFeedbackState>> odometryProducer,
            IProducer<GyroscopeMessage> gyroProducer,
            string robotConfigFolder,
            int requiredGyroMeasurementsForCalibration)
            : base(name, DefaultSyncTolerance)
        {
            this.gyroProducer = gyroProducer.Name;
            this.odometryProducer = odometryProducer.Name;
            this.robotConfigFolder = robotConfigFolder;
            this.requiredGyroMeasurementsForCalibration = requiredGyroMeasurementsForCalibration;
        }

        /// <summary>
        /// The odometry producer
        /// </summary>
        protected override string ProducerName1
        {
            get { return this.odometryProducer; }
        }

        /// <summary>
        /// The gyro producer
        /// </summary>
        protected override string ProducerName2
        {
            get { return this.gyroProducer; }
        }

        /// <summary>
        /// Initialize the agent.
        /// </summary>
        /// <param name="locator">The agent locator.</param>
        /// <remarks>Comments like these are useless but StyleCop makes me do it!</remarks>
        public override void Initialize(AgentLocator locator)
        {
            base.Initialize(locator);
            this.gyroCalibration = DataLoader<GyroCalibration>.ImportData(Path.Combine(this.robotConfigFolder, GyroCalibration.Filename));
            if (this.gyroCalibration == null)
            {
                throw new System.ArgumentException(
                    string.Format(
                   "Could not load {0} info from {1}, using default values for gyro calibration. This could result in bad odometry for navigation/slam",
                   GyroCalibration.Filename,
                   this.robotConfigFolder));
            }            
        }

        /// <summary>
        /// Activates this agent and all its upstream producers
        /// </summary>
        public override void OnActivated()
        {
            base.OnActivated();
            this.virtualDriveFeedback = new VirtualDriveFeedback(
                gyroCalibrationThreshold: this.gyroCalibration.GyroCalibrationThreshold,
                driftThresholdRadiansPerSecond: this.gyroCalibration.DriftThresholdRadiansPerSecond,
                slipThresholdPercentage: this.gyroCalibration.SlipThresholdPercentage,
                gyroYCalibrationFactor: this.gyroCalibration.GyroYCalibrationFactor,
                requiredGyroMeasurementsForCalibration: this.requiredGyroMeasurementsForCalibration);            
        }

        /// <summary>
        /// Join received drive and gyro messages.
        /// </summary>
        /// <param name="driveFeedbackMessage">The received odometry message</param>
        /// <param name="gyroMessage">The received gyro message</param>
        protected override void Receive(SimpleAgentMessage<DriveFeedbackState> driveFeedbackMessage, GyroscopeMessage gyroMessage)
        {            
            double gyroHeadingDelta = this.virtualDriveFeedback.GyroHeadingDelta(gyroMessage);
            Pose2D odometryDelta = this.virtualDriveFeedback.GetOdometryDelta(driveFeedbackMessage.State);
            DriveFeedbackState state = this.virtualDriveFeedback.GetUpdatedDriveFeedbackState(
                odometryDelta.Heading,
                gyroHeadingDelta,
                driveFeedbackMessage.State);

            this.Publisher.Post(new SimpleAgentMessage<DriveFeedbackState>(state, driveFeedbackMessage));
         }
    }
}
